<script>
import AMapLoader from '@amap/amap-jsapi-loader';

export default {
  name: "FourPage",
  data(){
    return{
      warnMsg:'',
      photoIndex:0,
      targetDetail:{
        name:'请选择你的兴趣点',
        cityname:'未选择',
        adname:'未选择',
        address:'未选择',
        location:{
          lat:30.536334,
          lng:114.364339
        },
        photos:[
          {
            title:'',
            url:''
          }
        ],
        rating:'请先选择',
        tel:'请先选择',
        type:'请先选择'
      },
      //model层传来的数据
      allPlanList:[],
      //处理时间后的数据
      planListTime:[],
      cityList:[
          '武汉',
          '北京',
          '项城',
          '常州'
      ],
      planList:[
        {
          planId:1,
          planName:'武汉一日游',
          planCity:'武汉',
          startTime:'2023-11-21-0',
          endTime:'2023-11-21-2',
          hotelName:'汉庭酒店（武汉大学店）',
          empty:'准备寒假出游'
        },
        {
          planId:2,
          planName:'武汉二日游',
          planCity:'武汉',
          startTime:'2023-11-21-0',
          endTime:'2023-11-21-2',
          hotelName:'汉庭酒店（武汉大学店）',
          empty: '准备暑假出游'
        },
        {
          planId:3,
          planName:'广州二日游',
          planCity:'广州',
          startTime:'2023-11-21-0',
          endTime:'2023-11-21-2',
          hotelName:'汉庭酒店（武汉大学店）',
          empty: '准备暑假出游'
        }
      ],
      currentPlanTargetList:[
        {
          targetId:1,
          targetName:'黄鹤楼',
          targetType:'必玩',
          tragetAddress:'湖北省武汉市武昌区蛇山西山坡特1号',
          importance:0,
          mustNight:0,
          targetLat:30.5363,
          targetLng:114.364
        },
        {
          targetId:2,
          targetName:'黄鹤楼',
          targetType:'必吃',
          tragetAddress:'湖北省武汉市武昌区蛇山西山坡特1号',
          importance:0,
          mustNight:1,
          targetLat:30.5363,
          targetLng:114.364
        },
        {
          targetId:3,
          targetName:'黄鹤楼',
          targetType:'必逛',
          tragetAddress:'湖北省武汉市武昌区蛇山西山坡特1号',
          importance:0,
          mustNight:0,
          targetLat:30.5363,
          targetLng:114.364
        },
      ],
      //逻辑数据
      currentPlanIndex:0,
      currentCityIndex:0,
      timeDetail:[
          '上午',
          '下午',
          '晚上'
      ],
      mustNight:[
          '任意',
          '晚上'
      ],
      importanceDetail:[
          '高',
          '中',
          '低'
      ]
    }
  },
  mounted() {
    //AAA运行时注释
    /*const first = {"planList":[{"planId":1,"planName":"中山两日游","cityName":"中山","startTime":"2023-12-10-0","endTime":"2023-12-12-2","hotelName":"如家酒店","hotelLat":0.0,"hotelLng":0.0,"empty":"default"},{"planId":2,"planName":"武汉一日游","cityName":"武汉","startTime":"2023-12-10-0","endTime":"2023-12-10-2","hotelName":"如家酒店（武汉大学店）","hotelLat":112.163475,"hotelLng":32.020909,"empty":"default"},{"planId":3,"planName":"武汉两日游","cityName":"武汉","startTime":"2023-12-10-0","endTime":"2023-12-11-2","hotelName":"如家酒店（武汉大学店）","hotelLat":0.0,"hotelLng":0.0,"empty":"default"},{"planId":4,"planName":"广州两日游","cityName":"广州","startTime":"2023-12-10-0","endTime":"2023-12-11-2","hotelName":"如家酒店","hotelLat":0.0,"hotelLng":0.0,"empty":"default"}],"cityName":"武汉"}
    this.init(first);*/

    this.$EventBus.$on('getAllPlans',(e)=>{
      this.init(e)
    })
    this.$EventBus.$on('getAllTargetsByPlanId',(e)=>{
      this.currentPlanTargetList = JSON.parse(JSON.stringify(e)).allTargets;
    })
    setTimeout(()=>{
      this.initMap()
    },2000)
  },
  methods:{
    initMap(){
      let that = this;
      AMapLoader.load({
        key: "dd2617cca23d86965b37a281144bfa49", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: [], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      })
          .then((AMap) => {
            this.map = new AMap.Map("container", {
              // 设置地图容器id
              viewMode: "3D", // 是否为3D地图模式
              zoom: 11, // 初始化地图级别
              center: [116.397428, 39.90923], // 初始化地图中心点位置
            });
          })
          .catch((e) => {
            console.log(e);
            that.warnMsg = e;
          });
    },
    mapShowHotel(hotelName,cityName){
      console.log(hotelName+cityName)
      AMapLoader.load({
        key: "dd2617cca23d86965b37a281144bfa49", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: [], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      })
          .then((AMap) => {
            if (this.map === null || this.map === undefined){
              setTimeout(()=>{
                this.mapShowHotel(hotelName,cityName)
              })
              return
            }
            var position = new AMap.LngLat(this.planList[this.currentPlanIndex].hotelLng, this.planList[this.currentPlanIndex].hotelLat);
            const marker = new AMap.Marker({
              position: new AMap.LngLat(this.planList[this.currentPlanIndex].hotelLng, this.planList[this.currentPlanIndex].hotelLat), //经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
              title: hotelName,
            });
            this.map.add(marker)
            this.map.setCenter(position)
          })
          .catch((e) => {
            console.log(e);
          });
    },
    mapShowTargets(newTargets){
      //暂时没做
      console.log(newTargets)
    },

    init(ee){
      this.allPlanList = JSON.parse(JSON.stringify(ee)).planList;
      const uniqueCities = new Set(this.allPlanList.map(plan => plan.cityName));
      this.cityList = Array.from(uniqueCities);
      const cityName = JSON.parse(JSON.stringify(ee)).cityName;
      this.currentCityIndex = this.cityList.indexOf(this.cityList.find(city => city === cityName))
      //根据cityName来决定planList
      this.setPlanList(cityName)
      //记录时间
      for (const plan of this.allPlanList) {
        this.planListTime.push({
          planId:plan.planId,
          startTimeDate:this.getTimeDate(plan.startTime),
          startTimeWhen:this.getTimeWhen(plan.startTime),
          endTimeDate:this.getTimeDate(plan.endTime),
          endTimeWhen:this.getTimeWhen(plan.endTime)
        })
      }
      this.getTargetsByPlan(this.planList[this.currentPlanIndex].planId);
      this.mapShowHotel(this.planList[this.currentPlanIndex].hotelName,this.planList[this.currentPlanIndex].cityName)
    },
    setPlanList(cityName){
      this.planList = this.allPlanList.filter(plan => plan.cityName === cityName);
    },
    getTimeDate(time){
      return time.slice(0, 10);
    },
    getTimeWhen(time){
      return Number(time.slice(-1));
    },
    //vue->WPF
    deletePlan(){
      this.$message.success('更新成功')
      window.bound.deletePlanByPlanId(this.planList[this.currentPlanIndex].planId);
    },
    changePlan(){

      this.$message.success('更新成功')
      const startTimeDetail = this.planList[this.currentPlanIndex].startTime.slice(-2);
      let startTimeDate = this.planList[this.currentPlanIndex].startTime.slice(0,-2);

      if (startTimeDate.length !== 12){
        var dateObject = new Date(startTimeDate);
        var year = dateObject.getFullYear();
        var month = (dateObject.getMonth() + 1).toString().padStart(2, '0'); // 月份从0开始，需要加1
        var day = dateObject.getDate().toString().padStart(2, '0');
        startTimeDate = `${year}-${month}-${day}`;
        this.planList[this.currentPlanIndex].startTime = startTimeDate + startTimeDetail;
      }


      const endTimeDetail = this.planList[this.currentPlanIndex].endTime.slice(-2);
      let endTimeDate = this.planList[this.currentPlanIndex].endTime.slice(0,-2);

      if (endTimeDate.length > 12){
        var dateObject1 = new Date(endTimeDate);
        var year1 = dateObject1.getFullYear();
        var month1 = (dateObject1.getMonth() + 1).toString().padStart(2, '0'); // 月份从0开始，需要加1
        var day1 = dateObject1.getDate().toString().padStart(2, '0');
        endTimeDate = `${year1}-${month1}-${day1}`;
        this.planList[this.currentPlanIndex].endTime = endTimeDate + endTimeDetail;
      }


      console.log(this.planList[this.currentPlanIndex]);
      window.bound.updatePlan(this.planList[this.currentPlanIndex]);
    },
    deleteTarget(targetId){
      this.$message.success('更新成功')
      window.bound.deleteTargetByTargetId(targetId);
      this.currentPlanTargetList = this.currentPlanTargetList.filter(target => target.targetId!==targetId)
    },
    updateTarget(target){
      this.$message.success('更新成功')
      window.bound.updateTarget(target);
    },
    getTargetsByPlan(planId){
      window.bound?.getAllTargetsByPlanId(planId);
    },
    //生成旅行方案
    pageJump(){
      window.bound.jumpToFinalPlan(this.planList[this.currentPlanIndex].planId);
    },
    //查看当前兴趣点
    checkTarget(target){
      let that = this;
      AMapLoader.load({
        key: "dd2617cca23d86965b37a281144bfa49", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: [], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      })
          .then((AMap) => {
            AMap.plugin(["AMap.PlaceSearch"], function() {
              var keywords = target.targetName;
              var autoOptions = {
                city: that.cityList[that.currentCityIndex],
                extensions: 'all',
              }
              var placeSearch = new AMap.PlaceSearch(autoOptions);
              placeSearch.search(keywords,
                  function (status, result){
                    console.log(result)
                    if (status === 'complete'){
                      that.targetDetail = result.poiList.pois[0];
                      console.log(that.targetDetail)
                    }
                  }
              )
            });
          }).catch((e) => {
        console.log(e)
      })
    },

    //切换图片
    lastPhotoFuc(){
      if (this.photoIndex > 0){
        this.photoIndex -= 1;
      }else{
        this.photoIndex = this.targetDetail.photos.length-1;
      }
    },
    nextPhotoFuc(){
      if (this.photoIndex < this.targetDetail.photos.length-1){
        this.photoIndex += 1;
      }else{
        this.photoIndex = 0;
      }
    },
  },
  watch:{
    //更改城市更新城市列表
    currentCityIndex(newVal){
      this.currentPlanIndex = 0;
      this.setPlanList(this.cityList[newVal]);
    },
    //更改开始时间和结束时间更新currentPlan
    planListTime:{
      handler(newVal){
        for (const timeset of newVal) {
          if (this.planList.find(plan => plan.planId === timeset.planId)){
            this.planList.find(plan => plan.planId === timeset.planId).startTime = timeset.startTimeDate + '-'+timeset.startTimeWhen;
            this.planList.find(plan => plan.planId === timeset.planId).endTime = timeset.endTimeDate + '-'+timeset.endTimeWhen;
          }
        }
      },
      deep:true
    },
    //从wpf获取到当前planid下的target
    currentPlanIndex(newVal){
      this.getTargetsByPlan(this.planList[newVal].planId);
      this.mapShowHotel(this.planList[newVal].hotelName)
    },
    //获取到targets之后
    currentPlanTargetList(newVal){
      this.mapShowTargets(newVal)
    }
  }
}
</script>

<template>
  <div>
    <div>{{warnMsg}}</div>
    <!--标题-->
    <div class="target-head">计划：{{planList[currentPlanIndex].planName}}</div>
    <!--选择城市、计划-->
    <div class="city-plan-select">
      <div class="target-title1">选择当前计划</div>
      <div class="two-container two-container-col">
        <div class="city-plan-line">
          <div>选择城市：</div>
          <el-select size="small" v-model="currentCityIndex" :placeholder="cityList[currentCityIndex]">
            <el-option
                v-for="(item, index) in cityList"
                :key="index"
                :label="item"
                :value="index">
            </el-option>
          </el-select>
        </div>
        <div class="city-plan-line">
          <div>选择计划：</div>
          <el-select size="small" v-model="currentPlanIndex" :placeholder="planList[currentPlanIndex].planName">
            <el-option
                v-for="(item, index) in planList"
                :key="index"
                :label="item.planName"
                :value="index">
            </el-option>
          </el-select>
        </div>
      </div>
    </div>
    <!--计划设置-->
    <div class="plan-manage-container">
      <div class="target-title1">修改当前计划</div>
      <div class="two-container two-container-col">
        <div class="city-plan-line">
          <div>计划名称：</div>
          <el-input style="width: 204px" size="small" v-model="planList[currentPlanIndex].planName"/>
        </div>
        <div class="city-plan-line">
          <div>开始时间：</div>
          <el-date-picker
              size="small"
              style="width: 138px"
              v-model="planListTime.find(time => time.planId === planList[currentPlanIndex].planId).startTimeDate"
              type="date"
              placeholder="选择日期">
          </el-date-picker>
          <el-select style="width: 80px" size="small" v-model="planListTime.find(time => time.planId === planList[currentPlanIndex].planId).startTimeWhen" :placeholder="timeDetail[planListTime.find(time => time.planId === planList[currentPlanIndex].planId).startTimeWhen]">
            <el-option
                v-for="(item, index) in timeDetail"
                :key="index"
                :label="item"
                :value="index">
            </el-option>
          </el-select>
        </div>
        <div class="city-plan-line">
          <div>结束时间：</div>
          <el-date-picker
              size="small"
              style="width: 138px"
              v-model="planListTime.find(time => time.planId === planList[currentPlanIndex].planId).endTimeDate"
              type="date"
              placeholder="选择日期">
          </el-date-picker>
          <el-select style="width: 80px" size="small" v-model="planListTime.find(time => time.planId === planList[currentPlanIndex].planId).endTimeWhen" :placeholder="timeDetail[planListTime.find(time => time.planId === planList[currentPlanIndex].planId).endTimeWhen]">
            <el-option
                v-for="(item, index) in timeDetail"
                :key="index"
                :label="item"
                :value="index">
            </el-option>
          </el-select>
        </div>
        <div class="city-plan-line">
          <div>住宿酒店：</div>
          <div>{{planList[currentPlanIndex].hotelName}}</div>
        </div>
        <!--高德api选择酒店-->
        <div id="container" class="gaode-hotel-container">

        </div>
        <div class="city-plan-line">
          <div>计划备注：</div>
          <el-input size="small" style="width: 206px" v-model="planList[currentPlanIndex].empty"/>
        </div>
        <div class="city-plan-line current-plan-btn">
          <el-button size="small" @click="deletePlan" plain>删除</el-button>
          <el-button size="small" @click="changePlan" type="success" plain>更改</el-button>
        </div>
      </div>
    </div>
    <div class="line"></div>
    <!--兴趣点管理-->
    <div class="target-manage-container">
      <div class="target-title1">计划想去</div>
      <div class="two-container">
        <div class="target-detail-container">
          <!--图片，名称-->
          <div class="photo-container">
            <button @click="lastPhotoFuc" class="last-img-btn"><img class="btn-img" src="@/assets/left.png"></button>
            <div class="img-container">
              <img :src="targetDetail.photos[photoIndex].url">
              <div v-if="targetDetail.photos[photoIndex].url.length<1 || targetDetail.photos[photoIndex].url === null" class="un-chosen-show">请先选择兴趣点</div>
            </div>
            <button @click="nextPhotoFuc" class="next-img-btn"><img class="btn-img" src="@/assets/right.png"></button>
            <div class="photo-title">{{targetDetail.name}}</div>
            <div class="photo-rating">- 高德评分：{{targetDetail.rating}} -</div>
          </div>
          <!--详情-->
          <div class="detail-container">
            <div style="white-space: nowrap; overflow-x: scroll"><strong>类型：</strong> {{targetDetail.type}}</div>
            <div style="white-space: nowrap; overflow-x: scroll"><strong>城市：</strong> {{targetDetail.cityname}}</div>
            <div style="white-space: nowrap; overflow-x: scroll"><strong>城区：</strong> {{targetDetail.adname}}</div>
            <div style="white-space: nowrap; overflow-x: scroll"><strong>地址：</strong> {{targetDetail.address}}</div>
            <div style="white-space: nowrap; overflow-x: scroll"><strong>电话：</strong> {{targetDetail.tel}}</div>
          </div>

        </div>
        <div class="target-container">
          <div class="small-target-head">选择</div>
          <div class="small-target-scroller">
            <div v-for="item in currentPlanTargetList" :key="item.targetId">
              <div class="scroll-line">
                <div class="scroll-line1 scroll-x" style="width: 200px">名称：<strong>{{item.targetName}}</strong> </div>
                <div class="scroller-line1">
                  目标时间：
                  <el-select style="width: 84px" size="small" v-model="item.mustNight" :placeholder="timeDetail[item.wantTime]">
                    <el-option
                        v-for="(item, index) in mustNight"
                        :key="index"
                        :label="item"
                        :value="index">
                    </el-option>
                  </el-select>
                </div>
                <el-button size="small" @click="checkTarget(item)" plain>查看</el-button>
                <el-button size="small" @click="deleteTarget(item.targetId)" type="warning" plain>删除</el-button>
                <el-button size="small" @click="updateTarget(item)" type="success" plain>更改</el-button>
              </div>
            </div>
          </div>
        </div>
        <div class="goto-plan-container">
          <el-button type="primary" @click="pageJump" plain>一键生成旅行方案</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
  .target-head{
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 48px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    letter-spacing: 2px;
    font-weight: bolder;
  }
  .target-title1{
    position: absolute;
    left: 4px;
    top: 4px;
    font-size: 16px;
    font-weight: bold;
  }
  .two-container{
    position: absolute;
    top: 30px;
    left: 12px;
    right: 12px;
    bottom: 0;
    display: flex;
    flex-direction: column;
    align-items: center;
  }
  .two-container-col{
    display: flex;
    flex-direction: column;
    justify-content: space-around;
  }
  /*选择当前计划*/
  .city-plan-select{
    position: absolute;
    left: 0;
    width: 380px;
    top: 60px;
    height: 120px;
  }
  .city-plan-line{
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 90%;
  }
  .gaode-hotel-container{
    background-color: #eee;
    width: 90%;
    height: 180px;
  }
  .current-plan-btn{
    justify-content: space-between;
  }
  /*当前计划*/
  .plan-manage-container{
    position: absolute;
    top: 186px;
    bottom: 12px;
    left: 0;
    width: 380px;
  }
  .line{
    position: absolute;
    left: 365px;
    width: 1px;
    top: 100px;
    bottom: 32px;
    background-color: #ddd;
  }
  /*计划想去*/
  .target-detail-container{
    height: 50%;
    width: 100%;
    position: relative;
  }
  .target-manage-container{
    position: absolute;
    right: 0;
    bottom: 12px;
    left: 372px;
    top: 60px;
  }
  .target-container{
    height: calc(50% - 54px);
    width: 100%;
    position: relative;
  }
  .small-target-head{
    position: absolute;
    left: 8px;
    top: 8px;
  }
  .small-target-scroller{
    position: absolute;
    top: 34px;
    bottom: 0;
    right: 8px;
    left: 16px;
    overflow-y: scroll;
  }
  .goto-plan-container{
    width: 100%;
    height: 54px;
    display: flex;
    align-items: end;
    justify-content: center;
  }
  .scroll-line{
    width: 99%;
    padding-bottom: 4px;
    margin: 8px 0;
    border-bottom: 1px solid #888;
    display: flex;
    white-space: nowrap;
    align-items: center;
    justify-content: space-between;
  }
  .scroller-line1{
    display: flex;
    align-items: center;
    justify-content: center;
    width: 30%;
  }

  .last-img-btn{
    position: absolute;
    left: 0;
    top: 10px;
    bottom:80px;
    width: 40px;
    background-color: transparent;
    border: none;
    border-bottom-left-radius: 8px;
    border-top-left-radius: 8px;
  }
  .next-img-btn{
    position: absolute;
    right: 0;
    top: 10px;
    bottom: 80px;
    width: 40px;
    background-color: transparent;
    border: none;
    border-top-right-radius: 8px;
    border-bottom-right-radius: 8px;
  }
  .btn-img{
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%);
    width: 100%;
  }
  .img-container{
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    top: 10px;
    bottom: 80px;
    width: calc(100% - 90px);
    overflow: hidden;
    box-shadow: 2px 2px 4px rgba(0,0,0,0.2);
    background-color: #97c0ee88;
  }
  .img-container img{
    object-fit: cover;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%);
    width: 100%;
  }
  .un-chosen-show{
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%);
    color: white;
  }
  .photo-title{
    position: absolute;
    bottom: 34px;
    left: 10px;
    height: 40px;
    right: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    letter-spacing: 2px;
  }
  .photo-rating{
    position: absolute;
    bottom: 16px;
    height: 20px;
    left: 10px;
    right: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
  }
  .photo-container{
    position: absolute;
    left: 0;
    top: 10px;
    right: 200px;
    bottom: 0;
  }
  .detail-container{
    position: absolute;
    right: 0;
    width: 180px;
    top: 50%;
    height: 200px;
    transform: translateY(-50%);
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }

</style>